<template>
  <div class="aui-wrapper aui-page__login">
    <div class="aui-content__wrapper">
      <main class="aui-content">
        <div class="login-header">
          <div class="login-icon">
            <img src="@/assets/img/login_icon.png"
                 :alt="$t('clientPortalLogin.mspbots')">
          </div>
        </div>
        <div class="login-body">
          <h1>{{ $t('custom.login.welcome') }}</h1>
          <h5 style="font-weight:normal;">{{ $t('custom.login.welcomeTips') }}</h5>
          <el-form :model="dataForm"
                   :rules="dataRule"
                   size="small"
                   v-loading="loading"
                   ref="dataForm"
                   @keyup.enter.native="dataFormSubmitHandle()"
                   status-icon>
            <el-form-item prop="username">
              <el-input v-model.trim="dataForm.username"
                        :placeholder="$t('login.username')">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-user"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="dataForm.password"
                        type="password"
                        show-password
                        :placeholder="$t('login.password')">
                <span slot="prefix"
                      class="el-input__icon">
                  <svg class="icon-svg"
                       aria-hidden="true">
                    <use xlink:href="#icon-lock"></use>
                  </svg>
                </span>
              </el-input>
            </el-form-item>
            <el-form-item style="text-align:left;">
              <el-checkbox v-model="isRememberAccount">{{$t('clientPortalLogin.rememberAccount')}}</el-checkbox>
            </el-form-item>
            <el-form-item>
              <el-button size="small"
                         type="primary"
                         :loading="loading"
                         @click="dataFormSubmitHandle()"
                         class="w-percent-100">{{ $t('login.title') }}</el-button>
            </el-form-item>
            <el-form-item>
              <el-button size="small"
                         :loading="loading"
                         @click="goRegist()"
                         class="w-percent-100">{{ $t('regist.title') }}</el-button>
            </el-form-item>

          </el-form>
        </div>
        <div class="login-footer">
          <div style="color:#AAB2D5;font-weight:bold;display:flex;align-items:center;justify-content:space-between;">
            <div @click="toOtherPage('termsOfUse')">{{ $t('custom.login.termsOfUse') }}</div>
            <div @click="toOtherPage('compliance')">{{ $t('custom.login.compliance') }}</div>
            <div @click="toOtherPage('support')">{{ $t('custom.login.support') }}</div>
            <div @click="toOtherPage('contacts')">{{ $t('custom.login.contacts') }}</div>
          </div>
          <p style="color:#C2C9E9;">{{ $t('custom.login.tips') }}</p>
        </div>
      </main>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import { debounce } from 'lodash'
import { getUUID } from '@/utils'

export default {
  data () {
    return {
      dataForm: {
        username: '',
        password: '',
        uuid: ''
      },
      loading: false,
      isRememberAccount: false
    }
  },
  computed: {
    dataRule () {
      return {
        username: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur', pattern: '[^ \x22]+' },
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        password: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCaptcha()
    this.accountFill()
  },
  methods: {
    getCaptcha () {
      this.dataForm.uuid = getUUID()
    },
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return
        }
        this.dataForm.username = this.dataForm.username.trim()
        this.loading = true
        this.rememberAccount()
        this.$interface.login.webLoginApi(this.dataForm)
          .then(({ data: res }) => {
            this.loading = false
            if (res.code !== 0) {
              this.getCaptcha()
              return this.$message.error(res.msg)
            }
            this.setCookies(res.data)
            this.loginSuccess()
          }).catch(() => {
            this.loading = false
          })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    loginSuccess (data) {
      this.$interface.login.loginUserInfoApi().then(res => {
        this.loading = false
        if (res.data.code !== 0) {
          this.$store.commit('SET_API_LOAD_STATUS', false)
          return this.$message.error(res.data.msg)
        }
        this.$store.commit('SET_API_LOAD_STATUS', false)
        this.$store.commit('SET_LOGIN_USER_INFO', res.data.data)
        this.$store.state.contentTabs = window.SITE_CONFIG['routerWithForgetToken']
        this.$router.replace({ path: '/home' })
      })
        .catch(() => {
          this.loading = false
          this.$store.commit('SET_API_LOAD_STATUS', false)
        })
    },
    setCookies (data) {
      window.location.protocol === 'https:'? Cookies.set('token', data.token, { sameSite: 'None', secure: true }) : Cookies.set('token', data.token)
      window.location.protocol === 'https:'? Cookies.set('tenant_code', data.tenantCode, { sameSite: 'None', secure: true }) : Cookies.set('tenant_code', data.tenantCode)
      sessionStorage.setItem('isMySelfCode', data.tenantCode)
      sessionStorage.setItem('isMySelfName', data.tenantName)
    },
    goRegist () {
      this.$router.replace({ path: '/registAsAccount' })
    },
    toOtherPage (e) {
      const support = 'https://wiki.mspbots.ai/x/JogF'
      const contacts = 'https://mspbots.ai'
      const termsOfUse = 'https://mspbots.ai/termsofuse/'
      const compliance = 'https://mspbots.ai/privacy/'
      switch (e) {
        case 'termsOfUse':
          window.open(termsOfUse, '_blank')
          break
        case 'compliance':
          window.open(compliance, '_blank')
          break
        case 'support':
          window.open(support, '_blank')
          break
        case 'contacts':
          window.open(contacts, '_blank')
          break
        default:
          break
      }
    },
    rememberAccount () {
      if (this.isRememberAccount) {
        localStorage.setItem('portalaccounta', this.dataForm.username)
        localStorage.setItem('portalaccountb', this.dataForm.password)
      } else {
        localStorage.removeItem('portalaccounta')
        localStorage.removeItem('portalaccountb')
      }
    },
    accountFill () {
      this.$set(this.dataForm, 'username', localStorage.getItem('portalaccounta'))
      this.$set(this.dataForm, 'password', localStorage.getItem('portalaccountb'))
    }
  }
}
</script>
<style lang="scss" scoped>
.aui-page__login::before {
  background-image: none;
  background: #f2f4f8;
}
.aui-page__login .aui-content__wrapper {
  background-color: #f2f4f8;
}
.login-icon {
  width: 300px;
  height: 40px;
  img {
    width: 100%;
    height: 100%;
  }
}

.hide {
  display: none;
}

.login-footer > div > div {
  cursor: pointer;
}
</style>
